package smarthouse.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import smarthouse.conv.Conversions;
import smarthouse.dto.UserDTO;
import smarthouse.model.User;

/**
 * Session Bean implementation class UserDAO
 */
@Stateless
@Local
public class UserDAO implements UserDAORemote {

	@EJB
	HouseDAORemote houseDAO;

	@EJB
	PrivilegeDAORemote privilegeDAO;

	@EJB
	Conversions conv;

	@PersistenceContext
	EntityManager em;

	public UserDAO() {

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public UserDTO login(String username, String password) {

		TypedQuery<User> usersReturn = em.createNamedQuery("User.findAll",
				User.class);

		List<User> users = usersReturn.getResultList();

		for (User u : users) {
			if (username.equals(u.getUsername())
					&& password.equals(u.getPassword())) {
				return conv.user_C_2_DTO(u);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<UserDTO> getAllUsers() {
		TypedQuery<User> usersReturn = em.createNamedQuery("User.findAll",
				User.class);

		List<User> users = usersReturn.getResultList();
		List<UserDTO> usersDTO = new ArrayList<>();
		for (User u : users) {
			usersDTO.add(conv.user_C_2_DTO(u));
		}

		return usersDTO;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public UserDTO getUserbyId(int id) {
		TypedQuery<User> usersReturn = em.createNamedQuery("User.findAll",
				User.class);

		List<User> users = usersReturn.getResultList();
		for (User u : users) {
			if (u.getUserId() == id) {
				return conv.user_C_2_DTO(u);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addUser(UserDTO user) {
		User u = em.find(User.class, user.getUserId());

		if (u == null) {
			em.persist(conv.user_DTO_2_C(user));
			return true;
		} else {
			em.merge(conv.user_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean updateUser(UserDTO user) {
		User u = em.find(User.class, user.getUserId());

		if (u == null) {
			return false;
		} else {
			em.merge(conv.user_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removeUser(int id) {
		User u = em.find(User.class, id);

		if (u == null) {
			return false;
		} else {
			em.remove(u);
			return true;
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getLastUserId() {
		TypedQuery<User> usersReturn = em.createNamedQuery("User.findAll",
				User.class);

		List<User> users = usersReturn.getResultList();
		int lastId = 1;
		for (User u : users) {
			lastId = u.getUserId();
		}

		return lastId;
	}

}
